// Copyright 2011 Google
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

function Store(url) {
  this.url = url;
};

Store.prototype.get = function(key, callback, object) {
  this.request('GET', 'get', {key: key}, callback, object);
};

Store.prototype.history = function(key, callback, object) {
  this.request('GET', 'history', {key: key}, callback, object);
};

Store.prototype.put = function(key, value, callback, object) {
  this.request('POST', 'put', {key: key, value: value}, callback, object);
};

Store.prototype.sync = function(since, callback, object) {
  this.request('GET', 'sync', {since: since || 0}, callback, object);
};

Store.prototype.request = function(method, verb, args, callback, object) {
  log('request:', method, verb, args);

  var params = [];
  for (var name in args) {
    var value = JSON.stringify(args[name]);
    params.push(encodeURIComponent(name) + '=' + encodeURIComponent(value));
  }
  var url = this.url + '/' + verb + '?' + params.join('&');

  var xhr = new XMLHttpRequest();
  xhr.open(method, url, true);
  if (method == 'POST') {
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  }
  xhr.onreadystatechange = function(event) {
    if (xhr.readyState == 4) {
      var result = null;
      if (xhr.status == 200) {
        try {
          result = JSON.parse(xhr.responseText);
        } catch (e) {
          log('unparseable response:', xhr.responseText);
        }
      }
      log('result:', result);
      callback && callback.call(object, result);
    }
  }
  xhr.send('');
};
